#include <ncurses.h>
#include <cdk/cdk.h>
#include <cassert>
#include "terminal.h"
#include "window.h"
#include "color.h"

Factory<Terminal> Terminal::create;

struct Terminal::P {
  WINDOW* stdscr_;
  void init_color_map();
};

void Terminal::P::init_color_map() {
  start_color();
  const int maxcolors = 256;
  int fg = 0;
  int bg = 0;
  for(int p = 0; p < maxcolors; ++p) {
    init_pair(p, fg, bg);
    ++fg;
    if(fg == 8) {
      ++bg;
      fg = 0;
    }
  }
}

Terminal::Terminal() : Terminal(false) {
}

Terminal::Terminal(bool use_cdk_colormap) : p(new P) {
  static bool initterminal_success = (p->stdscr_ = initscr()) != NULL;
  assert(initterminal_success);
  if(use_cdk_colormap) {
    initCDKColor();
  } else {
    p->init_color_map();
  }
}

Terminal::~Terminal() {
  endwin();
  p->stdscr_ = nullptr;
}


